﻿using GPS.MODELS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GPS.DataAccessLayer;
using AutoMapper;
using PagedList;
using GPS.ENTITYS;
using GPS.COMMON;
using System.IO;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using Oracle.ManagedDataAccess.Client;
using System.Data;
using Microsoft.AspNet.Identity;
using GPS.GPS_DAL;


namespace GPS.Controllers.GPS_NghiepVu
{
    public class GPS_QuyetDinhTotNghiepController : Controller
    {
        DbContextHelper<GPS_NVContext> _db = Singleton<DbContextHelper<GPS_NVContext>>.Inst;
        public ApplicationUser getCurrentUser()
        {
            ApplicationDbContext dbUser = new ApplicationDbContext();
            string userId = User.Identity.GetUserId();
            ApplicationUser _currentUser = dbUser.Users.Find(userId);
            return _currentUser;
        }

        //
        // GET: /GPS_QuyetDinhTotNghiep/
        public ActionResult Index(ViewModelDDTTN_QD SearchModel)
        {
            SearchModel.DDTTN_QD_DVGTVT_MA = this.getCurrentUser().MA_TINHTP;
            initialCategorySearchAction(SearchModel);

            var entities = _db.Filter<DDTTN_QD>(o => (SearchModel.DDTTN_QD_DVGTVT_MA == null || o.DDTTN_QD_DVGTVT_MA == SearchModel.DDTTN_QD_DVGTVT_MA)
                                                             && (SearchModel.DDTTN_QD_SO_QD == null || o.DDTTN_QD_SO_QD.Contains(SearchModel.DDTTN_QD_SO_QD))
                                                             && (SearchModel.DDTTN_QD_NGAY_QD_TUNGAY == null || o.DDTTN_QD_NGAY_QD >= SearchModel.DDTTN_QD_NGAY_QD_TUNGAY)
                                                             && (SearchModel.DDTTN_QD_NGAY_QD_DENNGAY == null || o.DDTTN_QD_NGAY_QD <= SearchModel.DDTTN_QD_NGAY_QD_DENNGAY)
                                                             );


            entities = entities.OrderByDescending(o => o.ID).ToList();

            var pageIndex = SearchModel.Page ?? 1;
            SearchModel.SearchResults = entities.ToPagedList(pageIndex, GPS.COMMON.Constants.PageSize);

            ViewBag.TotalRow = entities.Count();

            return View(SearchModel);
        }

        //
        // Search: /GPS_QuyetDinhTotNghiep/
        public ActionResult Search(ViewModelDDTTN_QD SearchModel)
        {
            string _DVGTGT = this.getCurrentUser().MA_TINHTP;

            ViewBag.DVGTVT_MAs = new SelectList(_db.Filter<SDONVIGTVT>(o => o.DVGTVT_MAQL == "40"), "DVGTVT_MA", "DVGTVT_TEN");
            ViewBag.DEFAULT_VALUE_DDL = CategoryCommon.DEFAULT_VALUE_DDL;
            //SearchModel.DDTTN_QD_DVGTVT_MA = this.getCurrentUser().MA_TINHTP;
            //if (SearchModel.DDTTN_QD_DVGTVT_MA == null)
            //{
            //    SearchModel.Page = 1;
            //    SearchModel.SearchResults = (new List<DDTTN_QD>()).ToPagedList(1, GPS.COMMON.Constants.PageSize);
            //    return View(SearchModel);
            //}


            if (SearchModel.DDTTN_QD_DVGTVT_MA == null)
                SearchModel.DDTTN_QD_DVGTVT_MA = "40";



            var entities = _db.Filter<DDTTN_QD>(o => ((SearchModel.DDTTN_QD_DVGTVT_MA == null || SearchModel.DDTTN_QD_DVGTVT_MA == "40") || o.DDTTN_QD_DVGTVT_MA == SearchModel.DDTTN_QD_DVGTVT_MA)
                                                             && (SearchModel.DDTTN_QD_SO_QD == null || o.DDTTN_QD_SO_QD.Contains(SearchModel.DDTTN_QD_SO_QD))
                                                             && (SearchModel.DDTTN_QD_NGAY_QD_TUNGAY == null || o.DDTTN_QD_NGAY_QD >= SearchModel.DDTTN_QD_NGAY_QD_TUNGAY)
                                                             && (SearchModel.DDTTN_QD_NGAY_QD_DENNGAY == null || o.DDTTN_QD_NGAY_QD <= SearchModel.DDTTN_QD_NGAY_QD_DENNGAY)
                                                             );


            entities = entities.OrderByDescending(o => o.ID).ToList();

            var pageIndex = SearchModel.Page ?? 1;
            SearchModel.SearchResults = entities.ToPagedList(pageIndex, GPS.COMMON.Constants.PageSize);

            ViewBag.TotalRow = entities.Count();

            return View(SearchModel);
        }


        public ActionResult Create()
        {

            CrudModelDDTTN_QD model = new CrudModelDDTTN_QD();

            this.InitialCategoryCreateAction();

            return View(model);
        }


        [HttpPost]
        public ActionResult Create(FormCollection _form, CrudModelDDTTN_QD model)
        {
            List<string> lstKeyName = _form.AllKeys.ToList().Where(s => s.StartsWith("ddlDTTN_HD_SHV_MA_")).ToList<String>();
            List<int> lstInt = new List<int>();
            lstKeyName.ForEach(o => lstInt.Add(int.Parse(o.Split('_')[o.Split('_').Count() - 1])));

            if (ModelState.IsValid)
            {
                //Save Header

                DDTTN_QD _model = new DDTTN_QD();
                GPS.COMMON.Helpers.CopyObject<DDTTN_QD>(model, ref _model, new List<string> { "DDTTN_QD_ACTIVE" });

                //get max lich học
                _model.ID = EFSequence.GetNextValue("SEQ_DDTTN_QD_ID");
                _model.DDTTN_QD_NGUOINHAP = User.Identity.Name;
                _model.DDTTN_QD_NGAYNHAP = DateTime.Now;
                _db.Insert<DDTTN_QD>(_model);

                decimal Id = _model.ID;

                if (lstKeyName != null)
                {

                    for (int i = 0; i < lstInt.Count; i++)
                    {
                        DDTTN_HD _objDDTTN_HD = new DDTTN_HD();
                        GPS.COMMON.Helpers.GetValueForm<DDTTN_HD>(_form, lstInt[i], ref _objDDTTN_HD);
                        _objDDTTN_HD.ID = EFSequence.GetNextValue("SEQ_DDTTN_HD_ID");
                        _objDDTTN_HD.DTTN_HD_DTTN_QD_ID = Id;
                        _objDDTTN_HD.DTTN_HD_DVGTVT_MA = model.DDTTN_QD_DVGTVT_MA;
                        _objDDTTN_HD.DTTN_HD_NGUOINHAP = User.Identity.Name;
                        _objDDTTN_HD.DTTN_HD_NGAYNHAP = DateTime.Now;
                        _db.Insert<DDTTN_HD>(_objDDTTN_HD);
                    }

                }

                //this.Information(string.Format(FDB.Common.Constants.NOTIFY_ADD_SUCCESS, "Sản xuất giống thủy sản"));
                return RedirectToAction("Index");
            }
            else
            {
                TempData["_SUCCESS"] = "";
                this.InitialCategoryCreateAction();
                //build html :
                int maxID = 0;
                String strHTML = string.Empty; //this.GenderHTML(lstInt, _form, ref maxID);
                ViewBag.AddHTML = strHTML;
                ViewBag.sMaxID = maxID + 1;
                return View(model);
            }
        }


        public ActionResult Edit(decimal id)
        {
            DDTTN_QD model = _db.GetOne<DDTTN_QD>(o => o.ID == id);
            if (model == null)
            {
                return HttpNotFound();
            }

            CrudModelDDTTN_QD _model = new CrudModelDDTTN_QD();
            GPS.COMMON.Helpers.CopyObject<CrudModelDDTTN_QD>(model, ref _model, new List<string> { "DDTTN_QD_ACTIVE" });
            _model.ListDDTTN_HDs = _db.Filter<DDTTN_HD>(o => o.DTTN_HD_DTTN_QD_ID == id);
            this.InitialCategoryEditAction();

            return View(_model);
        }

        [HttpPost]
        public ActionResult Edit(FormCollection _form, CrudModelDDTTN_QD model)
        {
            List<string> lstKeyName = _form.AllKeys.ToList().Where(s => s.StartsWith("ddlDTTN_HD_SHV_MA_")).ToList<String>();
            List<int> lstInt = new List<int>();
            lstKeyName.ForEach(o => lstInt.Add(int.Parse(o.Split('_')[o.Split('_').Count() - 1])));

            if (ModelState.IsValid)
            {
                //Save Header

                DDTTN_QD _model = _db.GetOne<DDTTN_QD>(o => o.ID == model.ID);
                GPS.COMMON.Helpers.CopyObject<DDTTN_QD>(model, ref _model, new List<string> { "DDTTN_QD_ACTIVE", "DDTTN_QD_NGUOINHAP", "DDTTN_QD_NGAYNHAP" });

                //get max lich học
                // _model.ID = EFSequence.GetNextValue("SEQ_DDTTN_QD_ID");
                _model.DDTTN_QD_NGUOISUA = User.Identity.Name;
                _model.DDTTN_QD_NGAYSUA = DateTime.Now;
                _db.Update<DDTTN_QD>(_model);

                decimal Id = _model.ID;

                if (lstKeyName != null)
                {
                    //delete item detail cũ:
                    _db.Delete<DDTTN_HD>(o => o.DTTN_HD_DTTN_QD_ID == Id);
                    //Insert mới
                    for (int i = 0; i < lstInt.Count; i++)
                    {
                        DDTTN_HD _objDDTTN_HD = new DDTTN_HD();
                        GPS.COMMON.Helpers.GetValueForm<DDTTN_HD>(_form, lstInt[i], ref _objDDTTN_HD);
                        _objDDTTN_HD.ID = EFSequence.GetNextValue("SEQ_DDTTN_HD_ID");
                        _objDDTTN_HD.DTTN_HD_DTTN_QD_ID = Id;
                        _objDDTTN_HD.DTTN_HD_DVGTVT_MA = model.DDTTN_QD_DVGTVT_MA;
                        _objDDTTN_HD.DTTN_HD_NGUOINHAP = User.Identity.Name;
                        _objDDTTN_HD.DTTN_HD_NGAYNHAP = DateTime.Now;
                        _db.Insert<DDTTN_HD>(_objDDTTN_HD);
                    }

                }

                //this.Information(string.Format(FDB.Common.Constants.NOTIFY_ADD_SUCCESS, "Sản xuất giống thủy sản"));
                return RedirectToAction("Index");
            }
            else
            {
                TempData["_SUCCESS"] = "";
                this.InitialCategoryEditAction();
                //build html :
                model.ListDDTTN_HDs = new List<DDTTN_HD>();
                //build html :
                int maxID = 0;
                String strHTML = string.Empty; //this.GenderHTML(lstInt, _form, ref maxID);
                ViewBag.sEditHTML = strHTML;
                ViewBag.sMaxID = maxID + 1;
                return View(model);
            }
        }

        public ActionResult Delete(decimal id)
        {
            //Xóa thì làm như thế nào, có cho xóa hay không?
            return RedirectToAction("Index");
        }


        public void initialCategorySearchAction(ViewModelDDTTN_QD viewModel)
        {
            // ApplicationUser curUser = getCurrentUser();

            ViewBag.DVGTVT_MAs = new SelectList(_db.Filter<SDONVIGTVT>(o => o.DVGTVT_MA == viewModel.DDTTN_QD_DVGTVT_MA), "DVGTVT_MA", "DVGTVT_TEN");
            ViewBag.DEFAULT_VALUE_DDL = CategoryCommon.DEFAULT_VALUE_DDL;


        }

        public void InitialCategoryCreateAction()
        {

            ApplicationUser curUser = getCurrentUser();
            string _madvgtvt = curUser.MA_TINHTP;
            ViewBag.DVGTVT_MAs = new SelectList(_db.Filter<SDONVIGTVT>(o => o.DVGTVT_MA == _madvgtvt), "DVGTVT_MA", "DVGTVT_TEN");
            //  model.THANG = DateTime.Now.Month;

            //Load đối tượng:
            string sDGVs = "";
            _db.Filter<DGV>(o => o.GV_DVGTVT_MA == _madvgtvt).ForEach(d =>
            {
                sDGVs += "<option value=\"" + d.GV_MA + "\">" + d.GV_HODEM + " " + d.GV_TEN + "</option>";
            });

            ViewBag.DGVs = sDGVs;

            string sCVSHs = "";
            Singleton<GPS_HocVienDAO>.Inst.GPS_GET_SCVSHV().ForEach(d =>
            {
                sCVSHs += "<option value=\"" + d.CVSHV_MA + "\">" + d.CVSHV_TEN + "</option>";
            });

            ViewBag.CVSHs = sCVSHs;

            ViewBag.DEFAULT_VALUE_DDL = CategoryCommon.DEFAULT_VALUE_DDL;

            ViewBag.KH_MAs = new SelectList(Singleton<GPS_HocVienDAO>.Inst.GPS_GETDS_KHOAHOC_HOCVIEN(_madvgtvt), "KH_MA", "KH_TEN");

        }

        public void InitialCategoryEditAction()
        {

            ApplicationUser curUser = getCurrentUser();
            string _madvgtvt = curUser.MA_TINHTP;
            ViewBag.DVGTVT_MAs = new SelectList(_db.Filter<SDONVIGTVT>(o => o.DVGTVT_MA == _madvgtvt), "DVGTVT_MA", "DVGTVT_TEN");
            //  model.THANG = DateTime.Now.Month;

            //Load đối tượng:
            string sDGVs = "";
            _db.Filter<DGV>(o => o.GV_DVGTVT_MA == _madvgtvt).ForEach(d =>
            {
                sDGVs += "<option value=\"" + d.GV_MA + "\">" + d.GV_HODEM + " " + d.GV_TEN + "</option>";
            });

            ViewBag.DGVs = sDGVs;

            string sCVSHs = "";
            Singleton<GPS_HocVienDAO>.Inst.GPS_GET_SCVSHV().ForEach(d =>
            {
                sCVSHs += "<option value=\"" + d.CVSHV_MA + "\">" + d.CVSHV_TEN + "</option>";
            });

            ViewBag.CVSHs = sCVSHs;

            ViewBag.DEFAULT_VALUE_DDL = CategoryCommon.DEFAULT_VALUE_DDL;

            var khoahocs = Singleton<GPS_HocVienDAO>.Inst.GPS_GETDS_KHOAHOC_HOCVIEN(_madvgtvt); //_db.Filter<DKH>(o => o.KH_DVGTVT_MA == view.KH_LH_DVGTVT_MA);
            ViewBag.KH_MAs = new SelectList(khoahocs, "KH_MA", "KH_TEN");
        }

        [HttpPost]
        public ActionResult GPS_IMG_GV(string gv_ma)
        {

            List<DGV_IMG> lstData = new List<DGV_IMG>();
            var gvs = _db.GetOne<DGV>(o => o.GV_MA == gv_ma);
            DGV_IMG _o1 = new DGV_IMG();
            _o1.GV_ANHCD = gvs.GV_ANHCD;
            var john = lstData;
            return Json(new { gvs = john }, JsonRequestBehavior.AllowGet);

        }


        #region detail
        public ActionResult Detail(decimal id)
        {
            OneCrudModelDHV _model = new OneCrudModelDHV();
            var entryPoint = (from hv in _db.DbContext.DHVs
                              join hs in _db.DbContext.DHV_HS on hv.HV_MA equals hs.HV_HS_HV_MA
                              where hv.ID == id
                              select new
                              {
                                  HV_KH_MA = hv.HV_KH_MA,
                                  HV_HANGDT_MA = hv.HV_HANGDT_MA,
                                  HV_HANGDT_RANK = hv.HV_HANGDT_RANK,
                                  HV_HODEM = hv.HV_HODEM,
                                  HV_TEN = hv.HV_TEN,
                                  HV_GIOITINH = hv.HV_GIOITINH,
                                  HV_QUOCTICH_MA = hv.HV_QUOCTICH_MA,
                                  HV_NGAYSINH = hv.HV_NGAYSINH,
                                  HV_NOITT = hv.HV_NOITT,
                                  HV_NOITT_DVHC_MA = hv.HV_NOITT_DVHC_MA,
                                  HV_NOITT_DVHC_DVQL = hv.HV_NOITT_DVHC_DVQL,
                                  HV_NOICT = hv.HV_NOICT,
                                  HV_NOICT_DVHC_MA = hv.HV_NOICT_DVHC_MA,
                                  HV_NOICT_DVHC_DVQL = hv.HV_NOICT_DVHC_DVQL,
                                  HV_SOCMT = hv.HV_SOCMT,
                                  HV_NGAYCAPCMT = hv.HV_NGAYCAPCMT,
                                  HV_NOICAPCMT = hv.HV_NOICAPCMT,
                                  HV_MOTA = hv.HV_MOTA,
                                  HV_HS_SOHOSO = hs.HV_HS_SOHOSO,
                                  HV_HS_HANGDT_MA_GPLXDACO = hs.HV_HS_HANGDT_MA_GPLXDACO,
                                  HV_HS_TTXL_MA = hs.HV_HS_TTXL_MA,
                                  HV_HS_HOSO_MA = hs.HV_HS_HOSO_MA,
                                  HV_HS_DVGTVT_MA_NHANHS = hs.HV_HS_DVGTVT_MA_NHANHS,
                                  HV_HS_DONVICAPGPLXDACO = hs.HV_HS_DONVICAPGPLXDACO,
                                  HV_HS_SOGPLXDACO = hs.HV_HS_SOGPLXDACO,
                                  HV_HS_MAHTCAP = hs.HV_HS_NOICAPGPLXDACO,
                                  HV_HS_HANGGPLXDACO = hs.HV_HS_HANGGPLXDACO,
                                  HV_HS_NGAYCAPGPLXDACO = hs.HV_HS_NGAYCAPGPLXDACO,
                                  HV_HS_NOICAPGPLXDACO = hs.HV_HS_NOICAPGPLXDACO,
                                  HV_HS_NGAYINGIAYTN = hs.HV_HS_NGAYINGIAYTN,
                                  HV_HS_ANH = hs.HV_HS_ANH
                              }).FirstOrDefault();

            GPS.COMMON.Helpers.CopyObject<OneCrudModelDHV>(entryPoint, ref _model);
            initialCategoryDetailAction(_model);
            return PartialView("_Detail", _model);
        }

        public void initialCategoryDetailAction(OneCrudModelDHV _model)
        {
            _model.HV_HODEM = _model.HV_HODEM + " " + _model.HV_TEN;
            _model.HV_GIOITINH = _model.HV_GIOITINH == "M" ? "Nam" : "Nữ";

            string noitt = _model.HV_NOITT_DVHC_MA == null ? null : _db.GetOne<SDONVIHC>(x => x.DVHC_MA == _model.HV_NOITT_DVHC_MA).DVHC_TEN;
            string noittql = _model.HV_NOITT_DVHC_DVQL == null ? null : _db.GetOne<SDONVIHC>(x => x.DVHC_MA == _model.HV_NOITT_DVHC_DVQL).DVHC_TEN;
            _model.HV_NOITT = _model.HV_NOITT + ", " + noitt + ", " + noittql;

            string noict = _model.HV_NOICT_DVHC_MA == null ? null : _db.GetOne<SDONVIHC>(x => x.DVHC_MA == _model.HV_NOICT_DVHC_MA).DVHC_TEN;
            string noictql = _model.HV_NOICT_DVHC_DVQL == null ? null : _db.GetOne<SDONVIHC>(x => x.DVHC_MA == _model.HV_NOICT_DVHC_DVQL).DVHC_TEN;
            _model.HV_NOICT = _model.HV_NOICT + ", " + noict + ", " + noictql;

            _model.HV_HS_MAHTCAP = _model.HV_HS_MAHTCAP == null ? null : _db.GetOne<SHTCAPGPLX>(x => x.HTGPLX_MA == _model.HV_HS_MAHTCAP).HTGPLX_TEN;
            _model.HV_QUOCTICH_MA = _model.HV_QUOCTICH_MA == null ? null : _db.GetOne<SQUOCTICH>(x => x.QTICH_MA == _model.HV_QUOCTICH_MA).QTICH_TENVN;
            _model.HV_HS_TTXL_MA = _model.HV_HS_TTXL_MA == null ? null : _db.GetOne<STTXL>(x => x.TTXL_MA == _model.HV_HS_TTXL_MA).TTXL_TEN;
            _model.HV_HS_DVGTVT_MA_NHANHS = _model.HV_HS_DVGTVT_MA_NHANHS == null ? null : _db.GetOne<SDONVIGTVT>(x => x.DVGTVT_MA == _model.HV_HS_DVGTVT_MA_NHANHS).DVGTVT_TEN;
        }
        #endregion


    }

    public class DGV_IMG
    {
        public byte[] GV_ANHCD
        {
            get;
            set;
        }
        public string GV_ANHCDSTRING
        {
            get
            {
                string strImg = this.GV_ANHCD == null ? "" : Convert.ToBase64String(this.GV_ANHCD);
                return strImg;
            }
        }
    }

}